#include "stdafx.h"
#include "stdafx.h"
#include "Logger.h"
#include "Database\DBHelper.h"


static uint16_t   LogNumber  = 0;

CLogger::CLogger()
{
	
}


CLogger::~CLogger()
{
}



void CLogger::Log(CTime& time, LOG_EVENT evnt, int tag)
{	
	char context[64];


	if (evnt != LOG_EVENT_SYSTEM_TIME) {	
		sprintf_s(context, "%I64d, %d,%d", time.GetTime(), evnt, tag);
		CDBHelper::GetInstance().Insert("log", context);
		LogNumber++;
		
		
		if (LogNumber > LOG_MAX_COUNT) {
			Print("Log is too much");
			char condition[128];
			sprintf_s(condition, "time IN (SELECT time FROM log LIMIT %d OFFSET 0)", LOG_CUT_NUMBER);
			CDBHelper::GetInstance().Delete("log", condition);

			SQLiteStatement* stmtCnt = CDBHelper::GetInstance().Query("log", "count(*)");
			if (stmtCnt->NextRow()) {
				LogNumber = stmtCnt->ValueInt(0);
			}
			else {
				LogNumber  = 0;
			}	
			delete stmtCnt;
			Print("Log ---- %d", LogNumber);
		}
		else {
			Print("Log ---- %d", LogNumber);
		}
	}
	else {
		sprintf_s(context, "time = %I64d, key = %d, value = %d", time.GetTime(), evnt, tag);
		CDBHelper::GetInstance().Update("cookies", context);
	}
}



void CLogger::Init()
{
	SQLiteStatement* stmtCnt  = CDBHelper::GetInstance().Query("log", "count(*)");
	if (stmtCnt->NextRow()) {
		LogNumber  = stmtCnt->ValueInt(0);

	}
	else {
		LogNumber  = 0;
	}
	delete stmtCnt;
	

	Print("Current number of log is %d", LogNumber);
	
	__time64_t  time  = 0;
	SQLiteStatement* stmt  = CDBHelper::GetInstance().Query("cookies", "*");

	if (stmt->NextRow()) {
		time  = stmt->ValueInt(0);
	}
	else {
		time  = 0;
	}

	if(time > 0){
		Log(CTime(time), LOG_EVENT_POWER_OFF, 0);
	}

    delete stmt;
}


void CLogger::Reborn()
{
	CDBHelper::GetInstance().Delete("log", NULL);
	CDBHelper::GetInstance().Update("cookies", "time = 0, key = 0, value = 0");
}



uint16_t CLogger::GetLogNumber()
{
	return LogNumber;
}